package com.zyg.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping("")
    public String login() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session) {
        if (code != null && !code.equalsIgnoreCase(session.getAttribute("code").toString())) {
            return "redirect:/";
        }
        if (userService.login(user)) {
            return "redirect:/toindex";
        } else {
            return "redirect:/";
        }
    }

    @RequestMapping("/code")
    @ResponseBody
    public String code(HttpSession session) {
        session.removeAttribute("code");
        //调用hutool 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String code = lineCaptcha.getCode();
        session.setAttribute("code", code);
        //转化json64
        return JSON.toJSONString(lineCaptcha.getImageBase64());
    }
}
